<!--轮播图组件-->
<template>
    <div class="slider" ref="slider">
      <div class="slider-group" ref="sliderGroup">
        <!-- 插槽，用于插入组件 -->
        <slot></slot>
      </div>
      <div class="dots">
        <!--根据被选中的index绑定选中后的css属性-->
        <span class="dot" :class="{active: currentPageIndex === index}"
              v-for="(item, index) in dots" :key="index"></span>
      </div>
    </div>
</template>

<script type="text/ecmascript-6">
  import {addClass} from "common/js/dom"
  import BScroll from 'better-scroll'

  export default {
    props: { // 从父组件传递过来的参数
      loop: { // 是否轮播
        type: Boolean,
        default: true
      },
      autoPlay: { // 是否自动播放
        type: Boolean,
        default: true
      },
      interval: { // 轮播间隔时长
        type: Number,
        default: 4000
      }
    },
    data(){ // 变量
      return {
        dots: [],
        currentPageIndex: 0
      }
    },
    mounted() {
      setTimeout(() => {
        this._setSliderWidth()
        this._initDots()
        this._initSlider()

        if(this.autoPlay){
          this._play()
        }
      }, 20)

      // 监听resize
      window.addEventListener('resize', () => {
        if(!this.slider){
          return
        }
        this._setSliderWidth(true) // 重新设置宽度
        this.slider.refresh() // 刷新界面
      })
    },
    activated() { // 钩子函数，keep-alive组件激活时调用。该钩子在服务器端渲染期间不被调用。
      if(this.autoPlay){
        this._play()
      }
    },
    deactivated() { // 钩子函数，keep-alive组件停用时调用。该钩子在服务端渲染期间不被调用。
      clearTimeout(this.timer)
    },
    beforeDestroy(){ // 钩子函数，实例销毁之间调用
      clearTimeout(this.timer)
    },
    methods: {
      _setSliderWidth(isResize){ // 设置轮播图的宽度，并适配各个宽度
        this.children = this.$refs.sliderGroup.children  // 获取slot里的每个子元素

        let width = 0
        let sliderWidth = this.$refs.slider.clientWidth  // 获取整个轮播图的宽度
        for (let i = 0; i < this.children.length; i++) { // 遍历所有的item
          let child = this.children[i]
          addClass(child, 'slider-item')   // 为动态创建的item命名

          child.style.width = sliderWidth + 'px'  // item的宽度为整个屏幕的宽度
          width += sliderWidth   // 累加所有item的宽度
        }
        if(this.loop && !isResize){
          width += 2 * sliderWidth   // 因为是轮播，所有设置轮播图长度的2倍
        }
        this.$refs.sliderGroup.style.width = width + 'px'  // 动态设置轮播图的宽度css
      },
      _initSlider(){ // 初始化better-scroll
        this.slider = new BScroll(this.$refs.slider, {
          scrollX: true,
          scrollY: false,
          momentum: false, // // 是否开启动量动画，关闭可以提升效率
          snap: {
            loop: this.loop,
            snapThreshold: 0.3, // 可滚动到下一个的阈值
            snapSpeed: 400
          },
        })

        // 滑到底部事件监听
        this.slider.on('scrollEnd', this._onScrollEnd)

        this.slider.on('touchend', () => {
          if(this.autoPlay){
            this._play()
          }
        })

        this.slider.on('beforeScrollStart', () => {
          if(this.autoPlay){
            clearTimeout(this.timer)
          }
        })
      },
      _onScrollEnd(){
        let pageIndex = this.slider.getCurrentPage().pageX
        this.currentPageIndex = pageIndex
        if(this.autoPlay){
          this._play()
        }
      },
      _initDots(){
        // 轮播图的点点的长度为图片的个数
        this.dots = new Array(this.children.length)
      },
      _play() { // 播放
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.slider.next()
        }, this.interval)
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"

  .slider
    min-height 1px
    .slider-group
      position relative
      overflow hidden
      white-space nowrap   // 不换行
      .slider-item
        float left
        box-sizing border-box
        overflow hidden
        text-align center
        a
          display block
          width 100%
          overflow hidden
          text-decoration none
        img
          display block
          width 100%
    .dots
      position absolute
      right 0
      left 0
      bottom 12px
      text-align center
      font-size 0
      .dot
        display inline-block
        margin 0 4px
        width 8px
        height 8px
        border-radius 50%
        background $color-text-l
        &.active
          width 20px
          border-radius 5px
          background $color-text-ll
</style>
